using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Globalization;

namespace Lizk.SimpleHUD
{
#if !XBOX
    public class ColorConverter : ExpandableObjectConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(ColorS))
                return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (value is ColorS && destinationType == typeof(string))
            {
                ColorS p = (ColorS)value;
                return p.R.ToString("X2") + p.G.ToString("X2") + p.B.ToString("X2") + p.A.ToString("X2");
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }


        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                try
                {
                    string s = (string)value;
                    if (s.Length == 8)
                        return new ColorS(byte.Parse(s.Substring(0, 2)), byte.Parse(s.Substring(2, 2)), byte.Parse(s.Substring(4, 2)), byte.Parse(s.Substring(6, 2)));
                    if(s.Length == 6)
                        return new ColorS(byte.Parse(s.Substring(0, 2)), byte.Parse(s.Substring(2, 2)), byte.Parse(s.Substring(4, 2)));
                    else throw new Exception();
                }
                catch
                {
                    throw new ArgumentException(
                        "Can not convert '" + (string)value +
                                           "' to type GeometryObject");
                }
            } 
            
            return base.ConvertFrom(context, culture, value);
        }

    }
#endif
}
